You are given a string s and a robot that currently holds an empty string t. Apply one of the following operations until s and t are both empty:
Remove the first character of a string s and give it to the robot. The robot will append this character to the string t.
Remove the last character of a string t and give it to the robot. The robot will write this character on paper.
Return the lexicographically smallest string that can be written on the paper.
簡單來說我們有一個字串s和空字串t,然後有兩個行爲可以做:
我過了很久都想不到該怎麼解,
加上我的偏頭痛又發作了,最終決定求助chatgpt...我只負責了筆記註釋
它似乎是使用了模擬的方法
(用Stack來模擬字串t,堆疊符合後進先出的原則,適合模擬字符的添加和移除。)
class Solution {
public String robotWithString(String s) {
// 存放t的堆疊
Stack<Character> stack = new Stack<>();
// 字串結果
StringBuilder result = new StringBuilder();
// 將s轉換成字元陣列,方便操作!
char[] chars = s.toCharArray();
// 儲存每個字元右邊最小的字元
char[] rightMin = new char[chars.length];
// 計算每個位置後方的最小字母,方便後續比對
rightMin[chars.length - 1] = chars[chars.length - 1];
for (int i = chars.length - 2; i >= 0; i--) {
rightMin[i] = (char) Math.min(chars[i], rightMin[i + 1]);
}
// 遍歷字串s,模擬將字母加入t
int i = 0;
while (i < chars.length || !stack.isEmpty()) {
// 當可以從s取字元並放入堆疊t時
if (i < chars.length && (stack.isEmpty() || stack.peek() > rightMin[i])) {
stack.push(chars[i]);
i++;
} else {
// 如果棧中字符比目前s中的字母字典序小,則取出並放到結果中
result.append(stack.pop());
}
}
return result.toString();
}
}
成功。